/**
 * 安卓端注册servlet
 */
package org.morningangel.servlet.android;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.morningangel.android.bean.ActivityBeanList;
import org.morningangel.bean.Activity;
import org.morningangel.bean.User;
import org.morningangel.dao.MainPushDao;
import org.morningangel.dao.UserDao;
import org.morningangel.dao.impl.MainPushDaoImpl;
import org.morningangel.dao.impl.UserDaoImpl;
import org.morningangel.util.EncryptUtil;

@WebServlet(name = "AndroidRegisterServlet", urlPatterns = "/android/register")
public class RegisterServlet extends HttpServlet {

	private static final long serialVersionUID = -5016601997370831219L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String phone = request.getParameter("telNum");
		String password = request.getParameter("password");
		UserDao userDao = new UserDaoImpl();
		MainPushDao mainPushDao= new MainPushDaoImpl();
		User user = userDao.login(phone);
		ActivityBeanList result = null;
		if (user != null) {
			result = new ActivityBeanList();
		} else {
			user = new User();
			user.setPhone(phone);
			user.setUsername("匿名");
			user.setPassword(EncryptUtil.md5(password));
			user.setRegisterTime(new Date());
			userDao.register(user);
			user = userDao.login(phone);
			List<Activity> activities = mainPushDao.getActivitys(1);
			result = new ActivityBeanList(user, 1, activities);
		}
		
		JSONObject jsonObject = JSONObject.fromObject(result);
		PrintWriter out = response.getWriter();
		out.print(jsonObject.toString());
		out.flush();
		out.close();
	}
	
}
